package com.module.base.pop.base

import android.view.View
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import com.kingja.loadsir.core.LoadService
import com.module.base.base.loadsir.LoadSirRegister
import com.module.base.base.loadsir.LoadSirReloadListener
import com.module.base.network.exception.ServerException
import com.module.base.network.exception.emptyException
import com.module.frame.ext.loadDialogShareFlow
import com.module.frame.ext.postEvent

/**
 * Author: yanxuwen
 * Date: 2023/5/17
 * Desc: 处理缺省图
 */
interface LoadSirReloadPopupImpl : LoadSirReloadListener {

    var loadService: LoadService<Any>?

    fun isFinishing(): Boolean

    fun <T : View> findViewById(@IdRes id: Int): T

    fun getErrorViewRes(): Int {
        return 0
    }

    /**
     * 是否有设置缺省图
     */
    private fun isErrorView(): Boolean {
        return getErrorViewRes() != 0
    }

    open fun initLoad() {
        if (isErrorView()) {
            //不要使用懒加载去初始化，因为里面有Handler().post导致初始化慢问题
            loadService = LoadSirRegister.register(this, findViewById(getErrorViewRes()))
        }
    }


    open fun showLoading() {
        if (loadService != null && loadService?.currentCallback == getLoadingCallback()) {
            //如果当前是加载试图，则不需要启动加载框
            return
        }
        postEvent(loadDialogShareFlow, true)
    }

    open fun hideLoading() {
        postEvent(loadDialogShareFlow, false)
    }


    /**
     * 重新加载，,界面会先空白，设置成加载界面
     */
    @CallSuper
    open override fun reload() {
        if (!isErrorView()) {
            return
        }
        loadService?.showCallback(getLoadingCallback())
    }

    /**
     * 刷新，保留现有的界面，展示出加载框
     */
    @CallSuper
    open fun refresh() {
        if (!isErrorView()) {
            return
        }
        showLoading()
    }

    open fun showSuccess() {
        if (isFinishing()) {
            return
        }
        hideLoading()
        if (!isErrorView()) {
            return
        }
        loadService?.showSuccess()
    }

    open fun showEmpty() {
        if (isFinishing()) {
            return
        }
        if (!isErrorView()) {
            return
        }
        try {
            loadService?.showWithConvertor(emptyException())
        } catch (e: Exception) {
            loadService?.showCallback(getEmptyCallback())
        }
    }

    open fun showError(exception: ServerException?) {
        if (isFinishing()) {
            return
        }
        if (!isErrorView()) {
            return
        }
        try {
            loadService?.showWithConvertor(exception)
        } catch (e: Exception) {
            loadService?.showCallback(getErrorCallback())
        }
    }

}